package com.zx.viewlearn.activity;

import android.content.Context;
import android.graphics.PixelFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import com.zx.viewlearn.R;

import static android.view.Gravity.TOP;

public class WindowLearnActivity1 extends AppCompatActivity {
    Button mFloatButton;
    WindowManager.LayoutParams mLayoutParams;
    WindowManager mWindowManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_window_learn1);
    }

    public void windowTest(View view) {
        if (mFloatButton != null) {
            return;
        }
        mFloatButton = new Button(this);
        mFloatButton.setText("window");


        mLayoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
//        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        mLayoutParams.gravity = Gravity.LEFT | TOP;
        mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

        mLayoutParams.x = 100;
        mLayoutParams.y = 100;
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        mWindowManager.addView(mFloatButton, mLayoutParams);


        mFloatButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int rawX = (int) event.getRawX();
                int rawY = (int) event.getRawY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mLayoutParams.x = rawX;
                        mLayoutParams.y = rawY;
                        mWindowManager.updateViewLayout(mFloatButton, mLayoutParams);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

}
